#include <iostream>
#include <unistd.h>
#include <sys/mman.h>


static void* systemAlloc(size_t pagesize)
{
    void* cur_brk = sbrk(0);
    printf("回收,cur_brk:%p\n", cur_brk);
    //使用sbrk
    void* ptr = sbrk(pagesize);
    if(ptr == (void*)-1)
    {
        //throw std::bad_alloc();
        return nullptr;
    }
    void* cur_brk1 = sbrk(0);
    void* expected_brk = (char*)ptr + pagesize;
    printf("回收,cur_brk1:%p, ptr:%p\n", cur_brk1, expected_brk);
    return ptr;
}

static void systemFree(void* ptr, size_t pagesize)
{
    void* cur_brk = sbrk(0);
    void* expected_brk = (char*)ptr + pagesize;

    printf("回收,cur_brk:%p, expected_brk:%p\n", cur_brk, expected_brk);
    //验证是否堆顶指针
    if(cur_brk == expected_brk)
    {
        printf("回收1,cur_brk:%p, expected_brk:%p\n", cur_brk, expected_brk);
        void* res = sbrk(-pagesize);
        if(res == (void*)-1)
        {
            printf("回收指针失败,pagesize:%u, ptr:%p", pagesize, ptr);
        }
    }
}

static void* systemAllocBig(size_t size)
{
    void* p = mmap(nullptr, size, PROT_WRITE | PROT_READ, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
    if(p == MAP_FAILED)
    {
        return nullptr;
    }
    return p;
}

static void systemFreeBig(void* ptr, size_t size)
{
    int res = munmap(ptr, size);
    if(res == -1)
    {
        printf("回收指针失败,pagesize:%u, ptr:%p", size, ptr);
    }
    printf("回收指针成功,pagesize:%u, ptr:%p\n", size, ptr);
}



int main()
{
    char* ptr = (char*)systemAllocBig(128 * 1024);
    if(ptr == nullptr)
    {
        printf("回收指针失败");
        return 1;
    }
    printf("申请内存成功 ptr:%p\n", ptr);
    ptr[0] = '1';
    ptr[1] = '1';
    ptr[2] = '1';
    ptr[3] = '\0';
    printf("%s\n", ptr);
    systemFreeBig(ptr, 128 * 1024);
    return 0;
}